package com.tiheima.filter;

import cn.hutool.core.util.ObjectUtil;
import com.tiheima.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.List;

/**
 * 令牌校验过滤器
 */
@Slf4j
// @WebFilter(urlPatterns = "/*")
public class LoginFilter implements Filter {

    /**
     * 过滤的方法
     * @param req  请求对象
     * @param resp 响应对象
     * @param chain  过滤器链
     */
    @Override
    public void doFilter(ServletRequest req,
                         ServletResponse resp,
                         FilterChain chain) throws IOException, ServletException {

        // 定义白名单
        List<String> whiteList = List.of("/login");
        // 参数强转
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        //1.获取请求路径
        String requestURI = request.getRequestURI();
        // 请求路径在白名单中
        if (whiteList.contains(requestURI)){
            // 放行
            chain.doFilter(request, response);
            return;
        }
        //2. 判断是否携带令牌
        String token = request.getHeader("token");
        // 既不是等请求，也没有携带令牌
        if (ObjectUtil.isNull(token)){
            // 响应一个401
            response.setStatus(401);
            return;
        }
        // 3. 解析令牌
        try {
            JwtUtils.parseJWT(token);
        }catch (Exception e){
            log.info("解析令牌失败，失败的原因：{}",e.getMessage());
            response.setStatus(401);
            return;
        }
        // 4. 放行
        log.info("解析令牌成功，请求路径：{}",requestURI);
        chain.doFilter(request, response);
    }
}
